import Taro from '@tarojs/taro';
import {http} from "./http"
import {newHttp} from "./request";
import {
  CREATE_RECHARGE_ORDER,
  GET_RECHARGE_PAY_PARAM,
  CERATE_REDIS,
  ORDER_LIST_PAY,
  NEW_PAY_PAY,
  NEW_PAY_REPAY,
  NEW_CREDIT_PAY,
  H5_ORDER_PAY,
  SURE_ORDER,
  SURE_NEW_ORDER, MOVIE_ORDER_CREATE, OLD_PAY_REPAY
} from "../constants/api"
import {PayParam, ServerData} from "./server.interface"
import {platform} from './platform-settting.service';
import {h5Wx} from "./h5.service";
import {lxH5Wx} from "./lx.h5.service";

class PaymentClass {

  async rechargePayment(total) {
    const data = {total_fee: total}
    Taro.showLoading({title: '创建订单中...'})
    const orderId = await http.post<number>(CREATE_RECHARGE_ORDER, data)
    Taro.hideLoading()
    if (!orderId) {
      return false
    }
    const payParam = await PaymentClass.getRechargePayParam(orderId)
    if (!payParam) {
      return false
    }
    return this.payment(payParam, false)
  }

  async orderPay(data) {
    let api = NEW_PAY_PAY
    if (data.useAccountPay == 3) {
      api = NEW_CREDIT_PAY
    }
    if (process.env.TARO_ENV === 'h5' && data.useAccountPay !== 3) {
      api = H5_ORDER_PAY
    }
    if (process.env.TARO_ENV === 'h5') {
      data['paySource'] = 'gongzhonghao'
    }
    const platformSet = await platform.getSetting();
    return new Promise<boolean>(async resolve => {
      if (platformSet && platformSet.payVersion === 1) {
        const result: any = process.env.P_ENV === 'lx' ? await newHttp.put_lxMerge(api + data.newPayOrderId, data) : await newHttp.put(api + data.newPayOrderId, data);
        if (result.statusCode === 200 || result.status === 200) {
          if (data.useAccountPay) {
            return resolve(true);
          } else {
            return resolve(await this.payment(result.data.data));
          }
        } else {
          if (result.data.status == '999') {
            Taro.showToast({
              title: result.data.message || result.data.msg || '支付失败！',
              icon: 'none',
              duration: 3000
            })
            return resolve(false)
          }
          if (result.data.message.length >= 14 || (result.data.msg && result.data.msg.length >= 14)) {
            Taro.showModal({
              content: result.data.message || result.data.msg || '支付失败！',
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          } else {
            Taro.showToast({
              title: result.data.message || result.data.msg || '支付失败！',
              icon: 'none',
              duration: 3000
            })
          }
          setTimeout(function () {
            if (result.data.status && result.data.status != '999') {
              let mpkey = ''
              const uInfo = Taro.getStorageSync('user') || ''
              if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
                mpkey = uInfo.mpkey
              }
              Taro.redirectTo({url: '/main/order/order?status=0' + '&mpkey=' + mpkey})
            }
          }, 2500)
          return resolve(false)
        }
      } else {
        const payParamRet = await http.postCondition<ServerData<PayParam>>(CERATE_REDIS, data)
        if (payParamRet && payParamRet.isOk) {
          const payParam = payParamRet.data
          if (payParam) {
            return resolve(await this.payment(payParam))
          } else {
            return resolve(false)
          }
        } else {
          return resolve(false)
        }
      }
    })
  }

  async moviePay(data) {
    return new Promise<boolean>(async resolve => {
      if (process.env.TARO_ENV === 'h5') {
        data['paySource'] = 'gongzhonghao'
      }
      const payParamRet = await http.postCar(MOVIE_ORDER_CREATE, data)
      if (payParamRet) {
        return resolve(await this.payment(payParamRet))
      } else {
        return resolve(false)
      }
    })
  }

  async newOrderPay(data) {
    return new Promise<boolean>(async resolve => {
      const result = await newHttp.put(SURE_ORDER, data);
      if (result.statusCode === 200) {
        return resolve(await this.payment(result.data.data));
      } else {
        Taro.showToast({
          title: result.data.message || '',
          icon: 'none',
          duration: 3000
        })
        return resolve(false)
      }
    })
  }

  async orderListPay(id, order_num) {
    let api = NEW_PAY_REPAY
    if (order_num.indexOf("A") == 0) {
      api = OLD_PAY_REPAY
    }
    const platformSet = await platform.getSetting();
    if (id) {
      Taro.showLoading({title: '获取支付信息中...'})
      let param: PayParam | false = false;
      if (platformSet && platformSet.payVersion === 1) {
        const paramRet = await newHttp.put(api + order_num, {});
        if ((paramRet.statusCode && paramRet.statusCode === 200) || (paramRet.status && paramRet.status === 200)) {
          param = paramRet.data.data;
        } else {
          if (paramRet.data.message && paramRet.data.message.length > 7) {
            Taro.showModal({
              title: '提示',
              content: paramRet.data.message,
            })
          } else {
            Taro.showToast({title: paramRet.data.message})
          }
          param = false;
        }
      } else {
        param = await http.post<PayParam>(ORDER_LIST_PAY, {orderId: id})
      }
      if (param) {
        Taro.hideLoading()
        return this.payment(param)
      }
      Taro.hideLoading()
    } else {
      Taro.showLoading({title: '获取支付信息中...'})
      let param: PayParam | false = false;
      const paramRet = await newHttp.put(SURE_NEW_ORDER + order_num, {});
      if ((paramRet.statusCode && paramRet.statusCode === 200) || (paramRet.status && paramRet.status === 200)) {
        param = paramRet.data.data;
      } else {
        if (paramRet.data.message && paramRet.data.message.length > 7) {
          Taro.showModal({
            title: '提示',
            content: paramRet.data.message,
          })
        } else {
          Taro.showToast({title: paramRet.data.message})
        }
        param = false;
      }
      if (param) {
        Taro.hideLoading()
        return this.payment(param)
      }
      Taro.hideLoading()
    }
  }

  private static async getRechargePayParam(orderId: number) {
    Taro.showLoading({title: '获取支付信息...'})
    const param = http.post<PayParam>(GET_RECHARGE_PAY_PARAM, {orderId})
    Taro.hideLoading()
    return param
  }

  jumpOrderList() {
    setTimeout(function () {
      let mpkey = ''
      const uInfo = Taro.getStorageSync('user') || ''
      if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
        mpkey = uInfo.mpkey
      }
      Taro.redirectTo({url: '/main/order/order?status=0' + '&mpkey=' + mpkey})
    }, 2000)
  }

  public async payment(payParam: any, jump = true, callback?: any): Promise<boolean> {
    return new Promise(resolve => {
      if (process.env.TARO_ENV === 'weapp') {
        Taro.requestPayment({...payParam}).then((res) => {
          if (callback) callback(res)
          return resolve(true)
        }).catch(err => {
          if (err.errMsg && err.errMsg.indexOf('cancel') > -1) {
            Taro.showToast({
              title: '取消支付', icon: 'none', duration: 2000, mask: true, success: res => {
                jump && this.jumpOrderList()
              }
            })
          } else {
            Taro.showToast({title: err.errMsg.split(':')[1] as string, icon: 'none'})
          }
          return resolve(false)
        })
      } else if (process.env.TARO_ENV === 'tt') {
        tt.createOrder({
          ...payParam,
          success() {
            resolve(true)
          },
          fail: res => {
            console.log(res)
            if (res.errNo === 4) {
              Taro.showModal({
                content: "支付取消",
                showCancel: false
              })
            } else {
              Taro.showModal({
                content: `${res.errMsg}, ${res.errNo}, ${res.errLogId}`,
                showCancel: false
              })
            }
            resolve(false)
          }
        })
      } else {
        if (process.env.P_ENV === 'lx') {
          lxH5Wx.lxPay(payParam, (res) => {
            resolve(res)
          })
        } else {
          const h5CodePay = Taro.getStorageSync("h5CodePay");
          h5Wx.chooseWXPay({...payParam}, res => {
            !!h5CodePay && h5CodePay === "h5CodePay" && callback("ok", res); // 二维码收款
            return resolve(true)
          }, err => {
            if (err.err_msg && err.err_msg.indexOf('cancel') > -1) {
              Taro.showToast({
                title: '取消支付', icon: 'none', duration: 2000, mask: true, success: res => {
                  if (jump) {
                    this.jumpOrderList()
                  } else {
                    // 二维码收款
                    !!h5CodePay && h5CodePay === "h5CodePay" && callback("fail", err);
                  }
                }
              })
            } else {
              Taro.showToast({title: err.errMsg.split(':')[1] as string, icon: 'none'})
            }
            return resolve(false)
          })
        }
      }
    })
  }
}

export const payment = new PaymentClass()
